/*
 * Copyright 2014 ptma@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.aisino.nmg.template.velocity;

import com.aisino.nmg.constant.GeneratorConstants;
import com.aisino.nmg.template.TemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class VelocityFactory implements TemplateEngine {
    private static final VelocityEngine velocityEngine = new VelocityEngine();

    public VelocityFactory(String classPath){
        final Properties props = new Properties();
        props.setProperty(Velocity.INPUT_ENCODING, GeneratorConstants.DEFAULT_ENCODING);
        props.setProperty(Velocity.OUTPUT_ENCODING, GeneratorConstants.DEFAULT_ENCODING);
        props.setProperty(Velocity.ENCODING_DEFAULT, GeneratorConstants.DEFAULT_ENCODING);
        props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
        props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, classPath + "templates/velocity");
        velocityEngine.init(props);
    }

    @Override
    public void process(Map<String, Object> model, String templateFileName, Writer writer) {
        Template template = velocityEngine.getTemplate(templateFileName, GeneratorConstants.DEFAULT_ENCODING);
        VelocityContext context = new VelocityContext(model);
        template.merge(context, writer);
        try {
            writer.close();
        } catch (IOException e) {
            log.error("关闭写入流失败:{}", templateFileName, e);
        }
    }
}
